import os
from pdf2image import convert_from_path

def pdf_to_images(pdf_path, output_folder):
  # 从 PDF 文件路径中提取文件名（不包含扩展名）
  file_name = os.path.splitext(os.path.basename(pdf_path))[0]
  # 指定 poppler 路径
  poppler_path = r'D:\poppler-24.08.0\Library\bin'
  # 将 PDF 文件的每一页转换为图像
  images = convert_from_path(pdf_path, poppler_path = poppler_path)
  # 遍历每一页转换后的图像
  for i, image in enumerate(images):
    # 生成图像的保存路径
    image_path = os.path.join(output_folder, f"{file_name}.jpg")
    # 保存图像
    image.save(image_path, 'JPEG')
    print(f"保存图片: {image_path}")

def convert_all_pdfs_in_folder(input_folder, output_folder):
  # 确保输出文件夹存在
  if not os.path.exists(output_folder):
    os.makedirs(output_folder)
  # 遍历输入文件夹中的所有文件
  for filename in os.listdir(input_folder):
    if filename.lower().endswith('.pdf'):
      pdf_path = os.path.join(input_folder, filename)
      pdf_to_images(pdf_path, output_folder)

if __name__ == "__main__":
  # 输入 PDF 文件所在的文件夹路径
  input_folder = r'D:\NodeTest\pdf'
  # 输出图片保存的文件夹路径
  output_folder = r'D:\NodeTest\pdf'
  convert_all_pdfs_in_folder(input_folder, output_folder)

# import os
# from pdf2image import convert_from_path
# from PIL import Image
#
# def pdf_to_images(pdf_path, output_folder, dpi = 300, format = 'JPEG', quality = 100):
#   """高保真转换PDF为图片
#   Args:
#       pdf_path: PDF文件路径
#       output_folder: 输出目录
#       dpi: 分辨率（默认300）
#       format: 图片格式（'JPEG'或'PNG'）
#       quality: JPEG质量（1-100）
#   """
#   file_name = os.path.splitext(os.path.basename(pdf_path))[0]
#   poppler_path = r'D:\poppler-24.08.0\Library\bin'
#
#   try:
#     images = convert_from_path(pdf_path, poppler_path = poppler_path, dpi = dpi, fmt = 'ppm'  # 内部使用无损格式转换
#     )
#
#     for i, image in enumerate(images):
#       # 处理CMYK色彩
#       if image.mode == 'CMYK':
#         image = image.convert('RGB')
#
#       # 生成输出路径
#       if format.upper() == 'PNG':
#         image_path = os.path.join(output_folder, f"{file_name}_page{i + 1}.png")
#         image.save(image_path, 'PNG', compress_level = 0)  # PNG无损
#       else:
#         image_path = os.path.join(output_folder, f"{file_name}_page{i + 1}.jpg")
#         image.save(image_path, 'JPEG', quality = quality)  # JPEG质量100
#
#       print(f"保存图片: {image_path} (DPI: {dpi}, Format: {format})")
#
#   except Exception as e:
#     print(f"转换失败: {pdf_path}\n错误: {e}")
#
# def convert_all_pdfs_in_folder(input_folder, output_folder, **kwargs):
#   if not os.path.exists(output_folder):
#     os.makedirs(output_folder)
#
#   for filename in os.listdir(input_folder):
#     if filename.lower().endswith('.pdf'):
#       pdf_path = os.path.join(input_folder, filename)
#       pdf_to_images(pdf_path, output_folder, **kwargs)
#
# if __name__ == "__main__":
#   input_folder = r'C:\Users\Administrator\Desktop\临时'
#   output_folder = r'C:\Users\Administrator\Desktop\临时'
#
#   # 调用示例（参数可调整）
#   convert_all_pdfs_in_folder(input_folder, output_folder, dpi = 300,  # 分辨率
#     format = 'PNG',  # 或 'JPEG'
#     quality = 100  # JPEG质量（1-100）
#   )
